from django.db.models import Q
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from unicodedata import category

from course.models import CourseModel
from course.ser import CourseSer
from home.models import CategoryModel
from home.ser import CategorySer
from utils.authentication import MyAuthentication


# Create your views here.
#方向
class Direction(APIView):
    def get(self, request):
       data=CategoryModel.objects.filter(is_del=False,parent=None).order_by('order')
       ser=CategorySer(data,many=True)
       return Response({'msg':'ok','code':200,'data':ser.data})

class Cate(APIView):
    def get(self, request):
        id=int(request.query_params.get('id'))
        if id !=0:
            data=CategoryModel.objects.filter(is_del=False,parent=id).order_by('order')
        else:
             # ~Q：用来取非的(也就是取反)
            # data=CategoryModel.objects.filter(Q(is_del=False),~Q(parent=None)).order_by('order')
            data=CategoryModel.objects.exclude(is_del=False,parent=None).order_by('order')
        ser=CategorySer(data,many=True)
        return Response({'msg':'ok','code':200,'data':ser.data})

class CoursePage(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    page_query_param = 'page'
# 课程列表
class Course(ListAPIView):
    queryset = CourseModel.objects.all()
    serializer_class = CourseSer
    pagination_class = CoursePage
    def get_queryset(self):
        query=Q()
        # 获取到分类的id以及方向的id
        cateid=int(self.request.query_params.get('cate'))  # 分类
        directionid=int(self.request.query_params.get('direction')) # 方向
        ordering=self.request.query_params.get('ordering','') # 排序
        level=self.request.query_params.get('level','')  #难度
        if cateid !=0:
            query&=Q(category=cateid)
        if directionid != 0 and cateid ==0:
            # 获取当前一级分类下的二级分类
            data=CategoryModel.objects.filter(is_del=False,parent=directionid)
            catelist=[]
            for i in data:
                catelist.append(i.id)
            query&=Q(category__in=catelist)
        if level:
            query&=Q(level=level)
        if ordering:
            return self.queryset.filter(query).order_by(ordering)
        else:
            return self.queryset.filter(query)

class Detail(APIView):
    def get(self,request):
        id = request.query_params.get('id')
        course=CourseModel.objects.filter(id=id).first()
        ser=CourseSer(course)
        return Response({'msg':'ok','code':200,'data':ser.data})

class Test(APIView):
    authentication_classes = [MyAuthentication]
    def get(self,request):
        return Response("Love!!")